package net.pluce.nxt.network.impl;


import java.io.IOException;

import lejos.pc.comm.NXTCommException;
import lejos.pc.comm.NXTCommFactory;
import lejos.pc.comm.NXTInfo;
import net.pluce.nxt.network.RobotConnection;
import net.pluce.nxt.network.RobotConnectionException;

public class BluetoothRobotConnection extends AbstractRobotConnection implements RobotConnection {

	protected NXTInfo nxtInfo = null;
	protected boolean connected = false;
	public BluetoothRobotConnection(String nxtName, String nxtAddress) throws RobotConnectionException{
		try {
			connection = NXTCommFactory.createNXTComm(NXTCommFactory.BLUETOOTH);
	      	nxtInfo = new NXTInfo(NXTCommFactory.BLUETOOTH,nxtName,nxtAddress);
		} catch (NXTCommException e) {
			throw new RobotConnectionException("Cannot initiate bluetooth connector: " + e.getMessage());
		}
	}

	@Override
	public boolean close() throws RobotConnectionException {
		if(connected){
			try {
				connection.close();
			} catch (IOException e) {
				throw new RobotConnectionException("Cannot close connection to robot: "+e.getMessage());
			}
			connected = false;
			return true;
		}
		return false;
	}

	@Override
	public boolean isOpened() {
		return connected;
	}
	@Override
	protected boolean initiate() throws RobotConnectionException {
		try {
			connected = connection.open(nxtInfo);
		} catch (NXTCommException e) {
			throw new RobotConnectionException("Cannot open connection to robot: "+e.getMessage());
		}
		return connected;
	}

}
